package com.bojiu.lawsearch.lawsearch.util;

import com.bojiu.lawsearch.lawsearch.mapper.AdminMapper;
import com.bojiu.lawsearch.lawsearch.mapper.EngineerMapper;
import com.bojiu.lawsearch.lawsearch.mapper.WechatUserMapper;
import com.bojiu.lawsearch.lawsearch.mapper.WxGoodsMapper;
import com.bojiu.lawsearch.lawsearch.model.Admin;
import com.bojiu.lawsearch.lawsearch.model.Engineer;
import com.bojiu.lawsearch.lawsearch.model.WechatUser;
import com.bojiu.lawsearch.lawsearch.model.WxGoods;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * @author: afdiao
 * @Date：2020/3/7 14:03
 * @Description:
 */
@Component
@Slf4j
public class AuthorizationHandle {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    WechatUserMapper wechatUserMapper;

    @Autowired
    WxGoodsMapper wxGoodsMapper;

    @Autowired
    EngineerMapper engineerMapper;

    /**
     * 校验后台人员登录token
     *
     * @param request
     * @param roles
     * @return
     */
    public JsonResult backHandler(HttpServletRequest request, String roles) {
        String sign = request.getHeader("sign");
        if (StringUtils.isEmpty(sign)) {
            log.error("sign is null");
            //返回用户为登录
            return new JsonResult(ResultCode.NO_SIGN);
        }
        try {
            String decrypt = EncryptUtil.decrypt(sign);
            JsonObject jsonObject = new Gson().fromJson(decrypt, JsonObject.class);
            String time = jsonObject.has("time") ? jsonObject.get("time").getAsString() : null;
            int userId = jsonObject.has("userId") ? jsonObject.get("userId").getAsInt() : null;
            Object user = adminMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, Admin.class));
            if (user == null || !((Admin) user).getLoginTime().equals(time)) {
                log.error("login time is error");
                return new JsonResult(ResultCode.NO_SIGN);
            }

            String userRole = jsonObject.has("role") ? jsonObject.get("role").getAsString() : null;
            if (!roles.contains(userRole)) {
                log.error("没有权限访问");
                return new JsonResult(ResultCode.NOAUTHENTION);
            }
            return new JsonResult(ResultCode.SUCCESS, userId);
        } catch (Exception e) {
            log.error("error to backHandler,error is :{}", e);
            return new JsonResult(ResultCode.NO_SIGN);
        }
    }

    /**
     * 判断应用端是否登录
     *
     * @param request
     * @return
     */
    public JsonResult webHandler(HttpServletRequest request) {
        String sign = request.getHeader("sign");
        if (StringUtils.isEmpty(sign)) {
            log.error("sign is null");
            //返回用户未登录
            return new JsonResult(ResultCode.NO_SIGN);
        }
        String decrypt = null;
        try {
            decrypt = EncryptUtil.decrypt(sign);
        } catch (Exception e) {
            try {
                String decode = URLDecoder.decode(sign, "UTF-8");
                log.debug("decode is :{}", decode);
                decrypt = EncryptUtil.decrypt(decode);
            } catch (Exception ex) {
                log.error("error to webHandler,error is :{}", e);
                ex.printStackTrace();
                return new JsonResult(ResultCode.NO_SIGN);
            }
        }
        JsonObject jsonObject = new Gson().fromJson(decrypt, JsonObject.class);
        int userId = jsonObject.has("userId") ? jsonObject.get("userId").getAsInt() : 0;
        String loginTime = jsonObject.has("loginTime") ? jsonObject.get("loginTime").getAsString() : null;
        if (userId == 0 || StringUtils.isEmpty(loginTime)) {
            log.error("用户id 或者登录时间为空");
            return new JsonResult(ResultCode.NO_SIGN);
        }
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        if (wechatUser.getGoodsId() == null || wechatUser.getGoodsId() == 0 || wxGoodsMapper.selectCountByExample(UtilTools.createExampleByKey("id", wechatUser.getGoodsId(), WxGoods.class)) == 0) {
            if (!loginTime.equals(wechatUser.getLoginTime())) {
                log.error("登录时间不一致，重新登录");
                return new JsonResult(ResultCode.NO_SIGN);
            }
        } else {
            WxGoods wxGoods = (WxGoods) wxGoodsMapper.selectOneByExample(UtilTools.createExampleByKey("id", wechatUser.getGoodsId(), WxGoods.class));
            //普通会员需要比较登录时间
            if (1 == wxGoods.getType()) {
                if (!loginTime.equals(wechatUser.getLoginTime())) {
                    log.error("登录时间不一致，重新登录");
                    return new JsonResult(ResultCode.NO_SIGN);
                }
            }
        }
        return new JsonResult(ResultCode.SUCCESS, userId);
    }

    /**
     * 判断该用户是否有会员权限
     *
     * @param isEngineer true 是工程师则免费使用   false 工程师也需要会员
     * @param userId
     * @return
     */
    public boolean memberHandle(int userId, boolean isEngineer) {
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        if (isEngineer) {
            if (wechatUser.getType() == 1) {
                return true;
            }
        }
        String memberTime = wechatUser.getMemberTime();
        if (StringUtils.isEmpty(memberTime)) {
            log.error("还没有开通会员");
            return false;
        }
        if (System.currentTimeMillis() / 1000 > Long.valueOf(memberTime)) {
            log.error("会员已经过期");
        }
        return true;
    }

    /**
     * 判断用户是否是工程师
     *
     * @param userId
     * @return true  是工程师    false 不是工程师
     */
    public boolean isEngineer(int userId) {
        if (engineerMapper.selectCountByExample(UtilTools.createExampleByKey("user_id", userId, Engineer.class)) == 0) {
            return false;
        } else {
            Engineer engineer = engineerMapper.getLastEngineer(userId);
            //判断是否已经认证过
            if (engineer.getIs_authentication() == 1) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 判断注册的时候有没有带上unionid
     *
     * @param request
     * @return
     */
    public JsonResult webRegisterHandler(HttpServletRequest request) {
        String sign = request.getHeader("sign");
        if (StringUtils.isEmpty(sign)) {
            log.error("sign is null");
            //返回用户为登录
            return new JsonResult(ResultCode.NO_SIGN);
        }
        try {
            String decode = URLDecoder.decode(sign, "UTF-8");
            log.debug("decode is :{}", decode);
            String decrypt = EncryptUtil.decrypt(decode);
            JsonObject jsonObject = new Gson().fromJson(decrypt, JsonObject.class);
            String unionid = jsonObject.has("unionid") ? jsonObject.get("unionid").getAsString() : null;
            if (StringUtils.isEmpty(unionid)) {
                log.error("unionid is null");
                return new JsonResult(ResultCode.NO_SIGN);
            }
            return new JsonResult(ResultCode.SUCCESS, unionid);
        } catch (Exception e) {
            log.error("error to webHandler,error is :{}", e);
            return new JsonResult(ResultCode.NO_SIGN);
        }
    }

}
